﻿package toolbar {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import toolbar.icon.Cursor;
	import toolbar.icon.Selected;
	import util.EventParser;
	
	public class IconButton extends Sprite {
		public var intro:String;
		protected var useSwitch:Boolean;
		protected var cursor:Cursor;
		protected var selected:Selected;
		
		public function IconButton(intro:String, bgWidth:int = 22):void {
			this.intro = intro;
			useSwitch = true;
			buttonMode = true;
			//鼠标移上和点击
			selected = new Selected(bgWidth);
			cursor = new Cursor(bgWidth);
			addChild(selected);
			addChild(cursor);
			//一系列侦听
			addEventListener(MouseEvent.MOUSE_OVER, onOverHandler);
			addEventListener(MouseEvent.MOUSE_OUT, onOutHandler);
			addEventListener(MouseEvent.MOUSE_DOWN, onDownHandler);
			addEventListener(MouseEvent.MOUSE_UP, onUpHandler);
		}
		
		private function onOverHandler(evt:MouseEvent):void {
			if (!useSwitch) {
				return;
			}
			if (cursor != null) {
				cursor.visible = true;
			}
			EventParser.dispatchOver(intro, evt.stageX, evt.stageY);
		}
		private function onOutHandler(evt:MouseEvent):void {
			if (!useSwitch) {
				return;
			}
			if (cursor != null) {
				cursor.visible = false;
			}
			EventParser.dispatchOut();
		}
		private function onDownHandler(evt:MouseEvent):void {
			if (!useSwitch) {
				return;
			}
			if (selected != null) {
				selected.visible = true;
			}
		}
		private function onUpHandler(evt:MouseEvent):void {
			if (!useSwitch) {
				return;
			}
			if (selected != null) {
				selected.visible = false;
			}
		}
		
		protected function addIcon(icon:Sprite):void {
			addChild(icon);
			icon.x = icon.y = 3;
		}
		
		public function show():void {
			alpha = 1;
			useSwitch = true;
			cursor.visible = false;
		}
		public function hide():void {
			alpha = 0.5;
			useSwitch = false;
		}
	}
}